import type { UserSystemsInterface } from '@/api/user-systems';
import { find } from 'lodash-es';
import { defineStore } from 'pinia';
import { parse, stringify } from 'zipson/lib';

export const useMicroAppStore = defineStore(
  'micro-app',
  () => {
    const microAppList = ref([] as UserSystemsInterface[]);
    const sysIdentifier = ref('');

    const currentApp = computed(() => {
      let appInfo = {} as UserSystemsInterface;
      // 从地址栏读取应用的唯一标识 比如 inp_doctor outp_docter
      const appName =
        new URLSearchParams(location.search).get('app') || sysIdentifier.value;
      if (appName) {
        sysIdentifier.value = appName;
        // 根据应用唯一标识 找到应用appId
        appInfo = find(
          microAppList.value,
          (app: UserSystemsInterface) => app.sysIdentifier === appName,
        ) as UserSystemsInterface;
      }
      return appInfo;
    });

    return {
      microAppList,
      sysIdentifier,
      currentApp,
    };
  },
  {
    persist: {
      storage: sessionStorage,
      serializer: {
        deserialize: parse,
        serialize: stringify,
      },
    },
  },
);
